﻿<textarea id="template_select" name="template_select" style="display:none">
<{$printTmpl.template_select}>
</textarea>
<textarea id="template_data" name="template_data" style="display:none">
<{if $printTmpl.template_data}>
<{$printTmpl.template_data}>
<{/if}>
</textarea>
<textarea id="jsondata_newdata" style="display:none">
<{$jsondata}>
</textarea>
<script type="text/javascript">
    (function() {
        $('printPreview_close').addEvent('click', function(){
            window.close();
        });
        if(typeof(WebSocket) == 'undefined') {
            $('printPreview_3_msg').setHTML('浏览器不支持WebSocket，无法使用菜鸟组件打印，建议使用最新Firefox');
            $('printPreview_3').style.display = 'block';
            return false;
        }
        /***
         *
         * 获取请求的UUID，指定长度和进制,如
         * getUUID(8, 2)   //"01001010" 8 character (base=2)
         * getUUID(8, 10) // "47473046" 8 character ID (base=10)
         * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
         *
         */
        function getUUID(len, radix) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;
            if (len) {
                for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
            } else {
                var r;
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random()*16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        }

        /***
         * 构造request对象
         */
        function getRequestObject(cmd) {
            var request  = new Object();
            request.requestID=getUUID(8, 16);
            request.version="1.0";
            request.cmd=cmd;
            return request;
        }

        function printerShow(data) {
            var temp = '<select id="printerlist" name="printerlist" class="x-input-select inputstyle" style="width:130px;">';
            Object.each(data.printers,function(i,index){
                var selected = '';
                if(i.name == data.defaultPrinter){
                    selected = ' selected="selected" ';
                }
                temp+='<option value="'+i.name+'" ' + selected + '>'+i.name+'</option>';
            });
            temp+='</select>';
            $('printerSpan').set('html', temp);
            printWaybill(documents, true);
            $('dly_printer_iframe').setHTML('预览文件生成中.......');
        }

        function afterSetPrintConfig(data) {
            if(data.status != "success") {
                var msg = data.msg ? data.msg : '打印机配置打开失败';
                alert(msg);
            }
        }

        function afterPrintRequest(data) {
            if(data.status == 'failed') {
                alert(data.msg);
            }
            if(data.previewURL) {
                $('dly_printer_iframe').setHTML('');
                var previewDiv = document.createElement('div');
                previewDiv.style.margin = '0 0 5px 0';
                previewDiv.setHTML('<a href="' + data.previewURL + '" target="_blank">下载/打开预览PDF文件</a>');
                previewDiv.inject($('dly_printer_iframe'));
                var previewIframe = document.createElement('iframe');
                previewIframe.width = '100%';
                previewIframe.height = '760px';
                previewIframe.src = data.previewURL;
                previewIframe.inject($('dly_printer_iframe'));
            }
        }

        var isPrintWaybill = false;
        function printWaybill(documents, preview) {
            if(!preview) {
                isPrintWaybill = true;
            }
            var objWaybill = getRequestObject("print");
            objWaybill.task = {};
            objWaybill.task.taskID = getUUID(8,10);
            objWaybill.task.preview = preview;
            objWaybill.task.printer = $('printerlist').value;
            var taskDocuments = [];
            documents.each(function(val, i) {
                taskDocuments[i] = {};
                taskDocuments[i].contents = val.contents;
                taskDocuments[i].documentID = (preview ? 1 : 0) + '_' + val.documentID;
            });
            objWaybill.task.documents = taskDocuments;
            webSocket.send(JSON.encode(objWaybill));
        }

        var allPrintData = JSON.decode($('jsondata_newdata').value);
        var customAreaUrl = '<{$printTmpl.custom_area_url}>';
        var templateSelect = JSON.decode($('template_select').value);
        var documents = new Array();
        allPrintData.each(function(printData){
            var jsonPacket = JSON.decode(printData.json_packet.replace(/“/g, '"'));
            var tmp = new Object();
            tmp.documentID = printData.batch_logi_no ? printData.batch_logi_no : printData.logi_no;
            var contents = new Array();
            contents[0] = new Object();
            contents[0] = jsonPacket;
            if(customAreaUrl) {
                contents[1] = new Object();
                contents[1]['templateURL'] = customAreaUrl;
                if(templateSelect) {
                    var customData = new Object();
                    templateSelect.each(function(i) {
                        customData[i] = printData[i];
                    })
                }
                contents[1]['data'] = customData;
            }
            tmp.contents = contents;
            documents[documents.length] = tmp;
        });

        var webSocket = new WebSocket('ws://127.0.0.1:13528');

        webSocket.onopen = function(event) {
            var request  = getRequestObject("getPrinters");
            webSocket.send(JSON.encode(request));
        };

        webSocket.onmessage = function(event) {
            $('printPreview_3').style.display = 'none';
            eval('var data = ' + event.data);
            switch(data.cmd) {
                case 'getPrinters':
                    printerShow(data);
                    break;
                case 'printerConfig':
                    afterSetPrintConfig(data);
                    break;
                case 'print':
                    afterPrintRequest(data);
                    break;
                case 'notifyPrintResult':
                    Object.each(data.printStatus, function(item) {
                        var dIDSplit = item.documentID.split('_', 2);
                        var oHtml = $('dly_printer').getHTML();
                        var msg = '<br/><span style="margin: 5px;font-weight: bold;">' + (dIDSplit[0] == 1 ? '预览' : '打印') +'</span>物流单号：' + dIDSplit[1] + ' ';
                        if(dIDSplit[0] == 0) {
                            isPrintWaybill = false;
                        }
                        if (item.status == 'success') {
                            oHtml += msg + '成功';
                        } else {
                            oHtml += msg + '失败：' + item.msg;
                        }
                        $('dly_printer').setHTML(oHtml);
                    });
                    break;
                default : break;
            }
        };

        webSocket.onerror = function(event) {
            $('printPreview_3_msg').setHTML('与菜鸟打印组件通信失败，确认是否已安装并打开淘宝组件,然后刷新页面');
            $('printPreview_3').style.display = 'block';
        };

        $('printerSetting').addEvent('click', function(){
            var rData = getRequestObject('printerConfig');
            webSocket.send(JSON.encode(rData));
        });

        if($('onlyprint_btn')) {
            $('onlyprint_btn').addEvent('click', function () {
                if(isPrintWaybill) {
                    alert('打印中，请耐心等待');
                    return false;
                }
                printWaybill(documents, false);
            });
        }
        var hasprintlist=[];
        if($('doprint_btn')) {
            $('doprint_btn').addEvent('click', function(){
                if(isPrintWaybill) {
                    alert('打印中，请耐心等待');
                    return false;
                }
                new Dialog(new Element("div.tableform",{html:'<div id="pause" class="division">正在提交...<{img app="desktop" src="loading.gif"}></div><div class="table-action"><{button label="关闭" onclick="re_finder();"}></div>'}),{
                    title:'提示',
                    width:230,
                    height:130,
                    modal:true,
                    resizeable:false}
                );
                if ($('printname')) {
                    var printname= $('printname').value;
                } else {
                    printname= '<{$vid}>';
                }
                if (hasprintlist.length>0){
                    for(var i=0;i<hasprintlist.length;i++){
                    if(hasprintlist[i] == printname )
                        if(confirm('您的选择含有已打印快递单，你确定要重复打印吗？')==false) {
                            window.close();
                        }
                    }
                }
                hasprintlist.push(printname);
                new Request({url:'index.php?app=wms&ctl=admin_receipts_print&act=setPrintStatus',method:'post',data:'type=express&str='+printname,
                    onSuccess:function(json){
                        if (json == 'true'){
                            $('pause').getParent('.dialog').retrieve('instance').close();
                            printWaybill(documents, false);
                        }else {
                            $('pause').set('text',json);
                        }
                    }
                }).send();
            });
        }
    })();
</script>